package com.dingdang.util;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ServerChat extends JFrame {
    private static final int PORT = 8888;
    private JTextArea sTa = new JTextArea();
    private JScrollPane sp = new JScrollPane(sTa);//创建滚动条
    private JPanel btnTool = new JPanel();
    private JButton startBtn = new JButton("启动");
    private JButton stopBtn = new JButton("停止");
    private ServerSocket serverSocket = null;
    private Socket socket = null;
    private boolean isStart = false;

    private List<ClientConn> clientConnList = new ArrayList<>();
//    方法的重载
    public ServerChat(){
        this.setTitle("服务器端");
        this.add(sp, BorderLayout.CENTER);
        btnTool.add(startBtn);
        btnTool.add(stopBtn);
        this.add(btnTool,BorderLayout.SOUTH);
        if (isStart){
            sTa.append("服务器已经启动了!\n");
        }else {
            sTa.append("服务器还没启动,请点击启动按钮!"+"\n");
        }
//        关闭窗口
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
               isStart =false;
                try {
                    if (serverSocket!=null) {
                        socket.close();
                    }
                    if (serverSocket!=null){
                        serverSocket.close();
                    }
                    sTa.append("服务器断开!\n");
                    System.out.println("服务停止");
                    System.exit(0);
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
        });
//        关闭按钮监听
        stopBtn.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {

                       if (serverSocket!=null||socket !=null) {
                           isStart=false;
                           sTa.append("服务器断开!\n");
                           System.exit(0);
                       }

            }
        });
//        启动按钮监听
        startBtn.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
//                在点击启动按钮是启动
                    try {
                        if (serverSocket==null) {
                            serverSocket = new ServerSocket(PORT);
                        }
                        isStart = true;
                        sTa.append("服务器已启动!"+"\n");

                    } catch (IOException ioException) {
                        ioException.printStackTrace();
                    }

            }
        });

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setBounds(0,0,400,500);
        sTa.setEnabled(false);
        this.setVisible(true);
        startServer();


    }
//    启动方法
    public void startServer(){
        try {
            serverSocket = new ServerSocket(PORT);
//            可以接收多个客户端的连接
            isStart= true;
            while (isStart) {
//            启动服务
                socket = serverSocket.accept();
//            把一个新的连接放到list集合中
                clientConnList.add(new ClientConn(socket));
                sTa.append("客户端连接服务器:"+socket.getInetAddress()+":"+socket.getPort()+"\n");
                System.out.println("客户端连接服务器:"+socket.getInetAddress()+":"+socket.getPort());
            }
        } catch (SocketException e) {
            System.out.println("服务器中断!");
            sTa.append("服务器中断!\n");
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
    //    关闭方法
    public void stopServer(){
        try {
            serverSocket = new ServerSocket(PORT);
//            可以接收多个客户端的连接
            isStart= false;
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

//    这个对象是属于服务器端的一个连接对象
    class ClientConn implements Runnable{
        Socket socket = null;
        public ClientConn(Socket socket){
            this.socket=socket;
//            创建线程
            (new Thread(this)).start();
        }
//     同时接受客户的-多线程接受数据
    @Override
    public void run() {
        try {
            DataInputStream dis = new DataInputStream(socket.getInputStream());
            while (isStart) {

                String str = dis.readUTF();
                System.out.println(socket.getPort()+"说:"+str+"\n");
                sTa.append(str+"\n");
                String strSend = socket.getPort() + "说:" + str + "\n";
                Iterator<ClientConn> iterator = clientConnList.iterator();
                while (iterator.hasNext()){
                    ClientConn next = iterator.next();
                    next.sendMessage(strSend);
                }
            }
        } catch (SocketException e) {
            System.out.println(socket.getPort()+"客户端线下");
            sTa.append(socket.getInetAddress()+":"+socket.getPort()+"客户端下线了!\n");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void sendMessage(String str){
        try {
            DataOutputStream dos = new DataOutputStream(this.socket.getOutputStream());
            dos.writeUTF(str);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
    public static void main(String[] args) {
        ServerChat chat = new ServerChat();
    }
}
